<template>
	<div>
		<el-card shadow="hover" body-style="padding:8px; ">
			<el-row justify="end" style="margin-bottom: 15px; margin-top: 3px">
				<el-col :span="8">
					<div style="float: left; height: 40px; width: 5px; background: green"></div>
					<div style="float: left; margin-top: 10px; margin-left: 20px; font-size: 16px">附件</div>
					<div style="float: left; margin-top: 11px; margin-left: 30px; font-size: 14px">{{ title }}</div>
				</el-col>
				<el-col :span="16" style="text-align: right">
					<el-button type="primary" icon="el-icon-uploadfilled" align="center" size="mini" @click="dialogVisible = true" v-if="isSameOrgan">上传</el-button>
					<el-button type="primary" icon="el-icon-camera" align="center" size="mini" @click="onCameraInfo" v-if="isSameOrgan">拍照</el-button>
					<el-button type="primary" icon="el-icon-delete" size="mini" @click="batDeleteAttach" v-if="isSameOrgan">批量删除</el-button>
					<el-button type="primary" icon="el-icon-refresh" size="mini" @click="batMathchEvi" v-if="isSameOrgan">关联</el-button>
					<el-button type="primary" icon="el-icon-download" size="mini" style="display: none">下载</el-button>
				</el-col>
			</el-row>
			<el-row>
				<el-table
					stripe
					ref="refTable"
					:data="tableData"
					size="mini"
					style="width: 100%"
					@selection-change="tableRowCheck"
					:row-class-name="tableRowClassName"
				>
					<el-table-column type="selection" width="55" />
					<el-table-column align="center" type="index" label="序号" width="60"></el-table-column>
					<el-table-column align="left" sortable label="文件名" show-overflow-tooltip>
						<template #default="scope">
							<a :href="scope.row.path" target="_blank">{{ scope.row.title }}</a>
						</template>
					</el-table-column>
					<el-table-column align="center" sortable label="上传时间" show-overflow-tooltip>
						<template #default="scope">
							{{ dateFormatTime(scope.row.createTime) }}
						</template>
					</el-table-column>
					<el-table-column align="center" property="eviNo" label="物品编号" show-overflow-tooltip></el-table-column>
					<el-table-column align="center" property="eviName" label="物品名称" show-overflow-tooltip></el-table-column>
					<el-table-column align="center" label="操作" width="200px">
						<template #default="scope">
							<el-button type="primary" plain size="mini" @click="onCancelMatch(scope.$index, scope.row)" v-if="scope.row.eviNo">取消关联</el-button>
							<el-button type="danger" plain size="mini" @click="handleDelFile(scope.$index, scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<el-pagination
					:page-sizes="[10, 20, 50, 100]"
					:page-size="query.pageSize"
					layout="prev, pager, next, jumper,total,sizes"
					:total="total"
					@size-change="onHandleSizeChange"
					@current-change="onHandleCurrentChange"
					prev-text="上一页"
					next-text="下一页"
					background
				>
				</el-pagination>
			</el-row>
		</el-card>
		<el-dialog v-model="dialogVisible" title="文件选择" width="30%">
			<el-upload
				class="upload-demo"
				:action="CaseAttachUploadUrl"
				:headers="customsHeaders"
				:data="imgData"
				:on-success="uploadSuccess"
				multiple
				ref="uploadRef"
				:auto-upload="false"
				:file-list="fileList"
			>
				<el-button type="primary" ref="btnUploadRef" style="display: none">select file</el-button>
			</el-upload>
			<template #footer>
				<span class="dialog-footer">
					<el-button type="primary" @click="btnUploadRef.$el.click()">文件选择</el-button>
					<el-button type="success" @click="uploadRef.submit()">确认上传</el-button>
				</span>
			</template>
		</el-dialog>
		<el-drawer v-model="dialogEviVisible" title="物品选择" :direction="direction" size="80%">
			<choiceEvience v-if="dialogEviVisible" ref="evidenceListRef" :caseid="query.caseid" @saveMath="saveMath" />
		</el-drawer>
		<el-drawer v-model="dialogAttachVisible" title="选择文书" :direction="direction" size="80%">
			<choiceAttach v-if="dialogAttachVisible" ref="attachListRef" :caseid="query.caseid" @loadDataRef="btnloadDataFromChoiceAttach" />
		</el-drawer>
	</div>
</template>

<script lang="ts">
import { ref, reactive, toRefs, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from '/@/store/index';
import { Session } from '/@/utils/storage';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getCaseAttach, deleteCaseAttach, matchCaseAttachToEvidence, cancelMatchCaseAttach ,UploadCamerAttr} from '/@/api/case/index';
import { CaseAttachUploadUrl } from '/@/common';
import { dateFormats, dateFormat,dateFormatTime } from '/@/common';
import choiceEvience from '/@/views/evidence/unit/component/choiceEvience.vue';
import choiceAttach from '/@/views/evidence/unit/component/choiceAttch.vue';
import { openCamera } from '/@/api/hardware/index';
import { queryImgs } from '/@/api/common';

export default {
	name: 'attachFile',
	components: { choiceEvience, choiceAttach },
	setup() {
		const refTable = ref(0);
		const router = useRouter();
		const store = useStore();
		const query = router.currentRoute.value.query;
		var title = '案件名称：' + query.caseName + (query.evidenceName ? '，物品名称：' + query.evidenceName + '。' : '。');
		const state = reactive({
			caseName: query.caseName,
			evidenceName: query.evidenceName,
			query: {
				caseid: query.caseid,
				evidenceId: query.evidenceId,
				page: 1,
				pageSize: 10,
			},
			imgData: {
				caseid: query.caseid,
				evidenceId: query.evidenceId || '',
			},
			isSameOrgan:query.isSameOrgan,
			title: title,
			dialogVisible: false,
			btnUploadDisabled: true,
			uploadRef: ref(0),
			btnUploadRef: ref(0),
			evidenceListRef: ref(0),
			tableData: [],
			tableSelection: [],
			total: 0,
			fileList: [],
			dialogEviVisible: false,
			dialogAttachVisible: false,
			imgurl:''
		});
		const handleDelFile = (pageIndex: any, row: any) => {
			ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
				confirmButtonText: '删除',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					deleteCaseAttach({ id: row.id }).then((res: any) => {
						if (res.success) {
							ElMessage({
								message: '删除成功',
								type: 'success',
							});
							loadData();
						} else {
							ElMessage.error('删除失败！');
						}
					});
				})
				.catch(() => {});
		};
		const onCancelMatch = function (pageIndex: any, row: any) {
			if (!row.eviName) {
				ElMessage.error('未关联');
				return;
			}
			cancelMatchCaseAttach({ attachId: row.id + '', caseid: row.caseId + '', evidenceId: state.query.evidenceId }).then((res: any) => {
				if (res.success) {
					ElMessage({
						message: '取消成功',
						type: 'success',
					});
					loadData();
				} else {
					ElMessage.error('取消失败！');
				}
			});
		};
		const customsHeaders = computed(() => {
			return {
				Authorization: `Bearer ${Session.get('token')}`,
			};
		});
		function tableRowClassName({ row, rowIndex }) {
			if (rowIndex === 1) {
				return 'warning-row';
			} else if (rowIndex === 3) {
				return 'success-row';
			}
			return '';
		}
		function uploadSuccess(response, uploadFile, uploadFiles) {
			if (uploadFiles) {
				ElMessage({
					message: '上传成功',
					type: 'success',
				});
				state.fileList = [];
				state.dialogVisible = false;
				loadData();
			}
		}

		function cameraUpload(url)
		{
           if(!url)
				return;
		
				UploadCamerAttr( query.caseid?query.caseid:0, query.evidenceId?query.evidenceId:0,url).then((res: any) => {
					loadData();
			});
		}

		function onCameraInfo() {
			store.dispatch('hardware/getHardwareConfigByKey', 'yjpz_gaopaiyi').then(function (cfg) {
				if (!cfg || !cfg.res1) {
					ElMessage('未配置【高拍仪配置】');
					return;
				}
				var ticks = new Date().getTime();
				console.log(ticks);
				var _typeid = 6;
				var _data = { key: cfg.res1, type: _typeid, relevanceNo: ticks, relevanceId:ticks,url: import.meta.env.VITE_API_URL + '/common/upload/base64img' };
				openCamera(_data).then(function(){
					queryImgs(ticks,_typeid).then(function(ret){
						if(ret.success){
							for(var i = 0;i<ret.data.length;i++){
								var _item = ret.data[i];
								cameraUpload(_item.url);
							}
						}
					});
				});
			});
		}

		function onHandleSizeChange(pageSize: number) {
			state.query.pageSize = pageSize;
			loadData();
		}
		function onHandleCurrentChange(pageIndex: any) {
			state.query.page = pageIndex;
			loadData();
		}
		async function loadData() {
			await getCaseAttach(state.query).then((res: any) => {
				if (res.success) {
					state.tableData = res.data.data;
					state.total = res.data.totalCount;
				}
			});
		}
		function batMathchEvi() {
			if (state.query.evidenceId) {
				//从具体物品进来关联文书
				state.dialogAttachVisible = true;
			} else {
				//关联物品
				if (state.tableSelection.length == 0) {
					ElMessage.warning('请选择要关联的记录！');
					return;
				}
				state.dialogEviVisible = true;
			}
		}
		function batDeleteAttach() {
			if (state.tableSelection.length == 0) {
				ElMessage.warning('请选择要删除的记录！');
				return;
			}
			var ids = state.tableSelection.map(function (a: any) {
				return a.id;
			});
			//批量删除文件
			ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
				confirmButtonText: '删除',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					deleteCaseAttach({ ids: ids }).then((res: any) => {
						if (res.success) {
							ElMessage({
								message: '删除成功',
								type: 'success',
							});
							loadData();
						} else {
							ElMessage.error('删除失败！');
						}
					});
				})
				.catch(() => {});
		}

		function saveMath(evidenceId: any) {
			var ids = state.tableSelection.map(function (a: any) {
				return a.id;
			});
			matchCaseAttachToEvidence({ ids: ids, evidenceId: evidenceId + '', caseid: state.query.caseid }).then((res: any) => {
				if (res.success) {
					ElMessage({
						message: '关联成功',
						type: 'success',
					});
					loadData();
					state.dialogEviVisible = false;
				} else {
					ElMessage.error('关联失败！');
				}
			});
		}
		function btnloadDataFromChoiceAttach() {
			loadData();
			state.dialogAttachVisible = false;
			console.log(1);
		}
		loadData();
		return {
			dateFormats,
			dateFormat,
			dateFormatTime,
			customsHeaders,
			uploadSuccess,
			refTable,
			tableRowCheck: function (selection: any) {
				state.tableSelection = selection;
			},
			batMathchEvi,
			batDeleteAttach,
			handleDelFile,
			CaseAttachUploadUrl,
			tableRowClassName,
			onHandleSizeChange,
			onHandleCurrentChange,
			saveMath,
			onCancelMatch,
			btnloadDataFromChoiceAttach,
			cameraUpload,
			onCameraInfo,
			...toRefs(state),
		};
	},
};
</script>
<style scoped>
.el-upload-list__item .el-icon-close {
	display: block;
	color: white;
	top: 10px;
	right: 10px;
}
.upload-demo {
	height: 450px;
	border: 1px solid #eee;
}
</style>
